package com.billdowney.qq.robot.plugins.provide.baidu.access;

import cn.hutool.http.HttpUtil;
import com.billdowney.qq.robot.bean.ConfigBean;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author BillDowney
 */
@Service
@Slf4j
public class AccessTokenService {

    @Autowired
    private ConfigBean configBean;
    @Autowired
    private ObjectMapper objectMapper;
    private AccessTokenResponse accessTokenResponse;

    public String getAccessToken() {
        if (accessTokenResponse == null || accessTokenResponse.isExpire()) {
            Map<String, Object> paramMap = new HashMap<>(3);
            paramMap.put("grant_type", "client_credentials");
            paramMap.put("client_id", configBean.getBaidu().getTokenClientId());
            paramMap.put("client_secret", configBean.getBaidu().getTokenClientSecret());
            try {
                log.info("准备获取新token:{}", paramMap);
                this.accessTokenResponse = objectMapper.readValue(HttpUtil.get(configBean.getBaidu().getTokenUrl(), paramMap), AccessTokenResponse.class);
                this.accessTokenResponse.setCreateTime(System.currentTimeMillis() - 10000);
            } catch (JsonProcessingException e) {
                throw new RuntimeException(e);
            }
            if (!this.accessTokenResponse.success()) {
                throw new RuntimeException(this.accessTokenResponse.getError() + ":" + this.accessTokenResponse.getErrorDescription());
            }
        }
        return this.accessTokenResponse.getAccessToken();
    }

}
